package com.example.test;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class ContentActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        TextView textView = (TextView) findViewById(R.id.callName);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            textView.setText("未允许读取通讯录权限！");
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            textView.setText(getQueryData());
        }
    }

    public String getAllPhoneNumbers(String lookUp_Key){
        StringBuilder allPhoneNo = new StringBuilder();
        //ContactsContract对应数据库contact2.db，是个模型类,以为这是个存电话号码的东西。其实，存电话号码只是它众多功能中一个比较常见且实用的功能。
        String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
        String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
        String[] selectionArgs = {lookUp_Key};
        //ContentResolver类型的实例对象，进而可以操作对应的数据。
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
        while(cursor.moveToNext()){
            allPhoneNo.append(cursor.getString(0)).append(" ");
        }
        return allPhoneNo.toString();
    }

    private CharSequence getQueryData() {

        StringBuilder stringBuilder = new StringBuilder();
        //getContentResolver()方法，用于获取一个ContentResolver对象
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,null,null,null);

        String name = ContactsContract.Contacts.DISPLAY_NAME;
        String key = ContactsContract.Contacts.LOOKUP_KEY;
        int displayNameIndex = cursor.getColumnIndex(name);
        int KeyIndex = cursor.getColumnIndex(key);
        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
            String displayName = cursor.getString(displayNameIndex);
            String Key = cursor.getString(KeyIndex);
            String displayPhone = getAllPhoneNumbers(Key);
            stringBuilder.append(displayName).append(" ").append(displayPhone).append("\n");
        }
        cursor.close();
        return stringBuilder.toString();
    }

}
